package com.ethink.gateway.error;

import com.ethink.framework.common.constant.CommonRespCode;
import com.ethink.framework.common.exception.BusinessException;
import com.ethink.framework.common.util.JacksonUtils;
import com.ethink.framework.common.web.response.CommonResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.handler.ResponseStatusExceptionHandler;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * <p>
 * 网关异常通用处理器，只作用在webflux 环境下 , 优先级低于 {@link ResponseStatusExceptionHandler} 执行
 */
@Slf4j
@Order(-1)
@RequiredArgsConstructor
@Component
public class GlobalExceptionHandler implements ErrorWebExceptionHandler {

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        CommonResponse commonResponse = new CommonResponse();
        ServerHttpResponse response = exchange.getResponse();
        if (response.isCommitted()) {
            return Mono.error(ex);
        }
        // header set
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        boolean logDetailEnable = false;
        if (ex instanceof BusinessException) {
            BusinessException businessException = (BusinessException) ex;
            commonResponse.setCode(businessException.getCode());
            commonResponse.setMessage(businessException.getMessage());
        } else if (ex instanceof ResponseStatusException) {
            logDetailEnable = true;
            ResponseStatusException statusException = (ResponseStatusException) ex;
            response.setStatusCode(statusException.getStatus());
            commonResponse.setCode(CommonRespCode.SYSTEM_ERR.getCode());
            commonResponse.setMessage(statusException.getMessage());
        } else {
            logDetailEnable = true;
            commonResponse.setCode(CommonRespCode.SYSTEM_ERR.getCode());
            commonResponse.setMessage(CommonRespCode.SYSTEM_ERR.getMessage());
        }
        String responseBody = JacksonUtils.toJson(commonResponse);
        if(logDetailEnable) {
            log.error("网关处理异常", ex);
        } else {
            log.error("网关处理异常", ex.getMessage());
        }
        log.info("response: {}", responseBody);
        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();
            return bufferFactory.wrap(responseBody.getBytes(StandardCharsets.UTF_8));
        }));
    }
}